package com.tl.boot.main.swagger;

import com.fasterxml.classmate.TypeResolver;
import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
import com.tl.boot.common.vo.ResponseVO;
import com.tl.boot.common.config.SwaggerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.AlternateTypeRule;
import springfox.documentation.schema.WildcardType;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * com.tl.boot.main.swagger -- Swagger2
 * Description:
 * Created by joshua_liu <a href="mailto:joshualwork@163.com"></a>
 * On 2019/9/19 10:42
 */
@Configuration
@EnableSwagger2
@EnableSwaggerBootstrapUI
public class Swagger2 {

    @Autowired
    private TypeResolver typeResolver;

    @Autowired
    private SwaggerConfig swaggerConfig;

    @Value("${spring.application.name}")
    private String groupName;

    private final static String SCAN_PACKAGE = "com.tl.boot.controller";

    @Bean
    public Docket createRestApi() {
        AlternateTypeRule alternateTypeRule = new AlternateTypeRule(
                typeResolver.resolve(ResponseVO.class),
                typeResolver.resolve(WildcardType.class));

        return new Docket(DocumentationType.SWAGGER_2)
//                .enable(!envUtil.isProduction())
                .groupName(groupName)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage(SCAN_PACKAGE))
                .paths(PathSelectors.any())
                .build()
                .alternateTypeRules(alternateTypeRule);
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(swaggerConfig.getTitle())
                .description(swaggerConfig.getDescription())
                .termsOfServiceUrl(swaggerConfig.getTermsOfServiceUrl())
                .contact(new Contact(swaggerConfig.getContactName(), swaggerConfig.getContactUrl(), swaggerConfig.getContactEmail()))
                .version(swaggerConfig.getVersion())
                .build();
    }

}
